package com.showcai.util;

import com.showcai.myRunTime.MyRunTimeExcption;
import com.showcai.tools.ToolsBase;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class ExcelIn extends ToolsBase {

    public static List<HashMap<Integer, String>> excelIn(String[] strList, MultipartFile file) {

        List<HashMap<Integer, String>> list = new ArrayList<>();
        InputStream is = null;

        try {
            is = file.getInputStream();
            Workbook workbook = getWorkbook(is, file.getOriginalFilename());
            if (workbook == null) {
                throw new MyRunTimeExcption("该文件不是excel文件");
            }
            Sheet sheet = workbook.getSheetAt(0);
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row row = sheet.getRow(rowNum);
                HashMap<Integer, String> map = new HashMap<>();
                //注意Poi读取的内容是有类型的，处理起来也jxl有所不同
                if (row == null) {
                    logger.info("row is null");
                    continue;
                }
                logger.info("row.getPhysicalNumberOfCells()==>>" + row.getPhysicalNumberOfCells());
                for (int i = 0; i < row.getPhysicalNumberOfCells(); i++) {
                    if (row.getCell(i) == null) {
                        logger.info("coll" + i + "is null");
                        continue;
                    }
                    if (row.getCell(i).getCellTypeEnum().equals(CellType.STRING)) {
                        map.put(i, row.getCell(i).getStringCellValue());
                    } else if (row.getCell(i).getCellTypeEnum().equals(CellType.NUMERIC)) {
                        map.put(i, String.valueOf(row.getCell(i).getNumericCellValue()));
                    }
                }
                logger.info("map.size" + map.size());
                logger.info("map is====?>>>>" + map.toString());
                if (map.size() > 0) {
                    list.add(map);
                }
                logger.info("list is====?>>>>" + list.size());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    private static Workbook getWorkbook(InputStream is, String fileName) throws IOException {
        Workbook workbook = null;
        if (fileName.toUpperCase().endsWith(".XLSX")) {
            workbook = new XSSFWorkbook(is);
        }
        if (fileName.toUpperCase().endsWith(".XLS")) {
            workbook = new HSSFWorkbook(is);
        }
        return workbook;
    }


}
